package cn.liu.jetpack_demo.components

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import cn.liu.jetpack_demo.R

@Composable
fun PasswordInputArea(
  placeholder: String = "Please enter password",
  label: String = "Password",
  onChange: (String) -> Unit = {},
) {
  Column(
    modifier = Modifier
      .background(Color.White),
    horizontalAlignment = Alignment.CenterHorizontally,
    verticalArrangement = Arrangement.Center
  ) {

    var password by rememberSaveable { mutableStateOf("") }
    // 显示/隐藏 密码状态
    var visible by remember { mutableStateOf(false) }

    val iconResource = if (visible) {
      R.drawable.eye_open
    } else {
      R.drawable.eye_closed
    }

    OutlinedTextField(
      modifier = Modifier
        .padding(16.dp),
      value = password,
      onValueChange = {
        password = it
        onChange(it)
      },
      placeholder = { Text(text = placeholder) },
      label = { Text(text = label) },
      trailingIcon = {
        IconButton(onClick = {
          visible = !visible
        }) {
          Icon(
            painter = painterResource(id = iconResource),
            contentDescription = "password visible"
          )
        }
      },
      keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
      // 显示/隐藏 密码
      visualTransformation = if (visible) {
        VisualTransformation.None
      } else {
        PasswordVisualTransformation()
      }

    )

  }
}

@Preview(name = "PasswordInputArea")
@Composable
private fun PreviewPasswordInputArea() {
  PasswordInputArea()
}